const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const joi = require('joi');
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        require: true,
        minlength: 2,
        maxlength: 20
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password: {
        type: String,
        required: true
    },
    // admin：超级用户
    // normal：普通用户
    role: {
        type: String,
        required: true
    },
    // 如果state=0，代表启用状态；1，代表禁用状态
    state: {
        type: Number,
        required: true,
        default: 0
    }
})
const User = mongoose.model('User', userSchema);
async function createUser() {
    const salt = await bcrypt.genSalt(10);
    const pass = await bcrypt.hash('123456', salt);
    const user = await User.create({
        username: '陈伟东',
        email: '1518372870@qq.com',
        password: pass,
        role: 'admin',
        state: 0
    });
}
// createUser();

const validateUser = user => {
    const schema = {
        username: joi.string().required().min(2).max(20).error(new Error('用户名非法')),
        email: joi.string().email().required().error(new Error('邮箱地址非法')),
        password: joi.string().regex(/^[a-zA-Z0-9]{3,30}$/).error(new Error('密码格式非法')), 
        role: joi.string().valid('admin', 'normal').error(new Error('角色值非法')),
        state: joi.number().valid(0, 1).required().error(new Error('状态值非法'))
    }
    return joi.validate(user, schema);
}

module.exports = {
    User,
    validateUser
}
